package hms.permissions;

public class PermissionSet implements respondsToPermissionRequests
{
	
	// Permissions are stored in string indexed with Permission.getGbOrder()
	String permissions;
	
	// DB Schema gives 24 chars to store password.
	// This lines defines the default to be all permissions denied.
	protected static final String defaultPermissionString = "000000000000000000000000";
	
	/**
	 * Empty Constructor - set permissions to default
	 */
	public PermissionSet() {
		permissions = new String(defaultPermissionString);
	}
	
	
	/**
	 * Constructor from string stored in database.
	 * 
	 * @param dbString String stored in database.
	 */
	public PermissionSet(String dbString) {
		permissions = dbString;
	}
	
	/**
	 * Check to see if a permission is granted.
	 * @param p Permission to check
	 * @return  True if granted, false if denied
	 */
	public boolean isPermissionGranted(Permission p) {
		return permissions.charAt(p.getDbOrder())=='1';
	}
	
	/**
	 * Return string to be saved to database.
	 * 
	 * @return String representing permissions.
	 */
	public String getDBString() {
		return permissions;
	}
	
	/**
	 * In case you need it, returns the default permission set used.
	 * 
	 * @return String representing default permission set.
	 */
	public String getDefaultPermissionSet() {
		return defaultPermissionString;
	}

	/**
	 * Allows you to grant permission p.
	 * 
	 * Example:
	 * MutablePermissionSet testPS = new MutablePermissionSet();
	 * testPS.grantPermission(Permission.FULL_ACCESS);
	 * 
	 * @param p Permission to be granted
	 */
	public void grantPermission(Permission p) {
		char[] workingSet = permissions.toCharArray();
		workingSet[p.getDbOrder()] = '1';
		permissions = new String(workingSet);
	}

	
	/**
	 * Allows you to revoke permission p.
	 * 
	 * Example:
	 * MutablePermissionSet testPS = new MutablePermissionSet();
	 * testPS.denyPermission(Permission.FULL_ACCESS);
	 * 
	 * @param p Permission to be revoked
	 */
	public void denyPermission(Permission p) {
		char[] workingSet = permissions.toCharArray();
		workingSet[p.getDbOrder()] = '0';
		permissions = new String(workingSet);
	}
}
